import 'animate.css'
import './assets/main.scss'

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { createPersistedStatePlugin } from 'pinia-plugin-persistedstate-2'

import App from './App.vue'
import router, { addDynamicRoute } from './router'
import { useMainStore } from './stores/mainStore'
import { getUserMenu } from '@/api/index'
import Cookies from 'js-cookie'
import ElementPlus from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhLocale from 'element-plus/es/locale/lang/zh-cn'

export const app = createApp(App)
const pinia = createPinia()

const installPersistedStatePlugin = createPersistedStatePlugin()
pinia.use((context) => installPersistedStatePlugin(context))

app.use(pinia)
const mainStore = useMainStore()

app.use(ElementPlus, { locale: zhLocale })

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

let faild = false

async function initApp() {
  try {
    const res = await fetch(import.meta.env.VITE_API_BASE_URL + '/auth/connect', {
      method: 'GET',
      headers: {
        Authorization: Cookies.get('quicklyToken') || ''
      }
    })
    const json = await res.json()

    if (json.code === 200) {
      const userMenuRes = await getUserMenu()
      if (userMenuRes.code === 200) {
        mainStore.menus = userMenuRes.data
        await addDynamicRoute(mainStore.menus)
      }
    } else if (json.code === 401 || json.code === 403) {
      faild = true
    }
  } finally {
    app.use(router)
    app.mount('#app')
    if (faild) {
      router.push({
        path: '/login'
      })
    }
  }
}

initApp()
